<?php

namespace app\api\service\pay;


use app\api\model\BoxCollect;
use app\api\service\coupon\MyCoupon;
use app\api\service\game\Point;
use app\api\service\User;
use app\common\enum\order\OrderStatus;
use app\common\enum\order\PayStatus;
use app\common\library\helper;
use app\common\model\Order;
use app\common\model\Seckill;
use think\facade\Db;
use think\facade\Log;

class SeckillOrderPay extends PaySuccess
{
    public function onSuccess(array $payment, int $payType)
    {
        Log::channel('wxpay')->info('订单号：'.$payment['order_no'].'开始处理秒杀订单');
        Db::startTrans();
        try{
            // 订单更新
            $order = Order::where('order_no', $payment['order_no'])->find();
            $order->pay_status = PayStatus::SUCCESS;
            $order->trans_no = $payment['transaction_id'];
            $order->order_status = OrderStatus::COMPLETED;
            $order->pay_time = time();
            $order->save();
            $seckill = Seckill::find($order->activity_id);
            //处理image_id
             $image_ids = $seckill->image_id;
             $image_id = $image_ids[0]['file_id'] ?? 0;

            //同时将商品移入用户盒柜
            BoxCollect::create([
                'user_id' => $order->user_id,
                'business' => 'seckill_order',
                'business_id' => $order->order_id,
                'goods_id' => $order->goods_id,
                'goods_source_id' => $order->goods_id,
                'goods_name' => $seckill->name,
                'image_id' => $image_id,
                'quantity' => 1,
                'activity_id' => $order->activity_id,
                'activity_name' => $seckill->name,
            ]);

            if($order->coupon_id > 0){
                //核销优惠券
                Log::channel('wxpay')->info('秒杀订单核销优惠券：'.$order->coupon_id);
                $res = app(MyCoupon::class)->destruction($order->user_id,$order->coupon_id,$order->order_id,$order->coupon_num);
                if(!$res){
                    return false;
                }
            }

            Db::commit();
            return true;
        }catch (\Exception $e){
            Db::rollBack();
            Log::channel('wxpay')->info('订单号：'.$payment['order_no'].'支付失败');
            Log::channel('wxpay')->info('失败原因：'.$e->getMessage());
            return false;
        }

    }

    public function callSuccess()
    {

    }
}